# -*- coding: utf-8 -*-

import json
import logging
from datetime import datetime
from odoo import http, fields
from odoo.http import request
from odoo.exceptions import ValidationError, AccessError
from .api_base import api_response, verify_api_token, check_department_permission
import base64
import io

_logger = logging.getLogger(__name__)


class EquipmentController(http.Controller):
    """设备管理控制器"""

    # ==================== 设备管理 ====================
    
    @http.route('/api/equipment/list', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    @verify_api_token
    # @check_api_permission('device:equipment:list')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def list_equipment(self, **kwargs):
        """获取设备列表"""
        page = kwargs.get('pageNum', 1)
        size = kwargs.get('pageSize', 10)
        name = kwargs.get('name', '')
        code = kwargs.get('code', '')
        status = kwargs.get('status', '')
        department_id = kwargs.get('departmentId', '')
        category_id = kwargs.get('categoryId', '')
        
        domain = []
        if name:
            domain.append(('name', 'ilike', name))
        if code:
            domain.append(('code', 'ilike', code))
        if status:
            domain.append(('status', '=', status))
        if department_id:
            domain.append(('department_id', '=', int(department_id)))
        if category_id:
            domain.append(('category_id', '=', int(category_id)))
        
        # 部门权限过滤
        current_user = getattr(request, 'current_api_user', None)
        if current_user:
            # 检查是否是admin账号，admin账号拥有全部权限
            # 检查用户ID是否为1（超级用户），或者login是否为admin
            is_admin = (current_user.id == 2 or current_user.login == 'admin')
            if is_admin:
                # admin账号可以看到所有设备，不添加过滤条件
                pass
            else:
                user_department = current_user.department_id
                if user_department:
                    # 检查用户是否是部门负责人
                    is_department_leader = user_department.leader_id and user_department.leader_id.id == current_user.id
                    
                    if is_department_leader:
                        # 部门负责人：可以看到该部门下的所有设备
                        domain.append(('department_id', '=', user_department.id))
                    else:
                        # 非部门负责人：只能看到绑定用户为自己的设备
                        domain.append(('user_id', '=', current_user.id))
                else:
                    # 没有部门信息，只能看到绑定用户为自己的设备
                    domain.append(('user_id', '=', current_user.id))
        
        # 计算总数 - 使用sudo()绕过ACL权限检查，因为API已通过JWT验证
        total = request.env['device.equipment'].sudo().search_count(domain)
        
        # 获取数据
        offset = (page - 1) * size
        equipments = request.env['device.equipment'].sudo().search(domain, offset=offset, limit=size)
        
        # 构建返回数据
        rows = []
        for equipment in equipments:
            rows.append({
                'equipmentId': equipment.id,
                'name': equipment.name,
                'code': equipment.code,
                'model': equipment.model,
                'categoryId': equipment.category_id.id if equipment.category_id else None,
                'categoryName': equipment.category_name,
                'departmentId': equipment.department_id.id if equipment.department_id else None,
                'departmentName': equipment.department_id.name if equipment.department_id else '',
                'workshopId': equipment.workshop_id.id if equipment.workshop_id else None,
                'workshopName': equipment.workshop_id.name if equipment.workshop_id else '',
                'userId': equipment.user_id.id if equipment.user_id else None,
                'userName': equipment.user_id.nick_name if equipment.user_id else '',
                'status': equipment.status,
                'purchaseDate': equipment.purchase_date.strftime('%Y-%m-%d') if equipment.purchase_date else '',
                'warrantyEndDate': equipment.warranty_end_date.strftime('%Y-%m-%d') if equipment.warranty_end_date else '',
                'lastMaintenanceDate': equipment.last_maintenance_date.strftime('%Y-%m-%d %H:%M:%S') if equipment.last_maintenance_date else '',
                'usageFrequency': equipment.usage_frequency,
                'usageHours': equipment.usage_hours,
                'maintenanceCount': equipment.maintenance_count,
                'trainingCount': equipment.training_count,
                'inspectionCount': equipment.inspection_count,
                'repairCount': equipment.repair_count,
                'createTime': equipment.create_time.strftime('%Y-%m-%d %H:%M:%S') if equipment.create_time else '',
                'remark': equipment.remark or ''
            })
        
        return {
            'code': 200,
            'msg': '查询成功',
            'data': {
                'total': total,
                'rows': rows
            }
        }

    @http.route('/api/equipment/info/<int:equipment_id>', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    @verify_api_token
    # @check_api_permission('device:equipment:read')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def get_equipment(self, equipment_id, **kwargs):
        """获取设备详情"""
        equipment = request.env['device.equipment'].sudo().browse(equipment_id)
        if not equipment.exists():
            return {'code': 404, 'msg': '设备不存在', 'data': None}
        
        data = {
            'equipmentId': equipment.id,
            'name': equipment.name,
            'code': equipment.code,
            'model': equipment.model,
            'description': equipment.description,
            'categoryId': equipment.category_id.id if equipment.category_id else None,
            'categoryName': equipment.category_name,
            'departmentId': equipment.department_id.id if equipment.department_id else None,
            'departmentName': equipment.department_id.name if equipment.department_id else '',
            'workshopId': equipment.workshop_id.id if equipment.workshop_id else None,
            'workshopName': equipment.workshop_id.name if equipment.workshop_id else '',
            'userId': equipment.user_id.id if equipment.user_id else None,
            'userName': equipment.user_id.nick_name if equipment.user_id else '',
            'managerId': equipment.manager_id.id if equipment.manager_id else None,
            'managerName': equipment.manager_id.nick_name if equipment.manager_id else '',
            'status': equipment.status,
            'purchaseDate': equipment.purchase_date.strftime('%Y-%m-%d') if equipment.purchase_date else '',
            'warrantyEndDate': equipment.warranty_end_date.strftime('%Y-%m-%d') if equipment.warranty_end_date else '',
            'lastMaintenanceDate': equipment.last_maintenance_date.strftime('%Y-%m-%d %H:%M:%S') if equipment.last_maintenance_date else '',
            'usageFrequency': equipment.usage_frequency,
            'usageHours': equipment.usage_hours,
            'createTime': equipment.create_time.strftime('%Y-%m-%d %H:%M:%S') if equipment.create_time else '',
            'updateTime': equipment.update_time.strftime('%Y-%m-%d %H:%M:%S') if equipment.update_time else '',
            'createBy': equipment.create_by,
            'updateBy': equipment.update_by,
            'remark': equipment.remark or '',
            # 附件URL信息
            'attachmentUrls': equipment.attachment_urls or '',
            'imageUrl': equipment.image_url or '',
            'manualUrl': equipment.manual_url or '',
            'certificateUrl': equipment.certificate_url or ''
        }
        
        return {
            'code': 200,
            'msg': '查询成功',
            'data': data
        }

    @http.route('/api/equipment/add', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    @verify_api_token
    # @check_api_permission('device:equipment:add')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def add_equipment(self, **kwargs):
        """新增设备"""
        name = kwargs.get('name')
        code = kwargs.get('code')
        model = kwargs.get('model', '')
        description = kwargs.get('description', '')
        category_id = kwargs.get('categoryId')
        department_id = kwargs.get('departmentId')
        workshop_id = kwargs.get('workshopId')
        user_id = kwargs.get('userId')
        manager_id = kwargs.get('managerId')
        status = kwargs.get('status', 'normal')
        purchase_date = kwargs.get('purchaseDate')
        warranty_end_date = kwargs.get('warrantyEndDate')
        usage_frequency = kwargs.get('usageFrequency', 'daily')
        usage_hours = kwargs.get('usageHours', 0.0)
        remark = kwargs.get('remark', '')
        
        # 附件URL相关字段
        attachment_urls = kwargs.get('attachmentUrls', '')
        image_url = kwargs.get('imageUrl', '')
        manual_url = kwargs.get('manualUrl', '')
        certificate_url = kwargs.get('certificateUrl', '')
        
        if not name or not code or not category_id or not department_id or not workshop_id:
            raise ValidationError('设备名称、设备编号、设备类别、所属部门、车间位置为必填项')
        
        vals = {
            'name': name,
            'code': code,
            'model': model,
            'description': description,
            'category_id': int(category_id),
            'department_id': int(department_id),
            'workshop_id': int(workshop_id),
            'status': status,
            'usage_frequency': usage_frequency,
            'usage_hours': float(usage_hours),
            'remark': remark,
            # 附件URL字段
            'attachment_urls': attachment_urls,
            'image_url': image_url,
            'manual_url': manual_url,
            'certificate_url': certificate_url
        }
        
        if user_id:
            vals['user_id'] = int(user_id)
        if manager_id:
            vals['manager_id'] = int(manager_id)
        if purchase_date:
            vals['purchase_date'] = datetime.strptime(purchase_date, '%Y-%m-%d').date()
        if warranty_end_date:
            vals['warranty_end_date'] = datetime.strptime(warranty_end_date, '%Y-%m-%d').date()
        
        equipment = request.env['device.equipment'].sudo().create(vals)
        
        return {
            'code': 200,
            'msg': '新增成功',
            'data': {'equipmentId': equipment.id}
        }

    @http.route('/api/equipment/edit', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    @verify_api_token
    # @check_api_permission('device:equipment:edit')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def edit_equipment(self, **kwargs):
        """修改设备"""
        equipment_id = kwargs.get('equipmentId')
        if not equipment_id:
            raise ValidationError('设备ID不能为空')
        
        equipment = request.env['device.equipment'].sudo().browse(int(equipment_id))
        if not equipment.exists():
            return {'code': 404, 'msg': '设备不存在', 'data': None}
        
        vals = {}
        if 'name' in kwargs:
            vals['name'] = kwargs['name']
        if 'code' in kwargs:
            vals['code'] = kwargs['code']
        if 'model' in kwargs:
            vals['model'] = kwargs['model']
        if 'description' in kwargs:
            vals['description'] = kwargs['description']
        if 'categoryId' in kwargs:
            vals['category_id'] = int(kwargs['categoryId'])
        if 'departmentId' in kwargs:
            vals['department_id'] = int(kwargs['departmentId'])
        if 'workshopId' in kwargs:
            vals['workshop_id'] = int(kwargs['workshopId'])
        if 'userId' in kwargs:
            vals['user_id'] = int(kwargs['userId']) if kwargs['userId'] else False
        if 'managerId' in kwargs:
            vals['manager_id'] = int(kwargs['managerId']) if kwargs['managerId'] else False
        if 'status' in kwargs:
            vals['status'] = kwargs['status']
        if 'purchaseDate' in kwargs:
            vals['purchase_date'] = datetime.strptime(kwargs['purchaseDate'], '%Y-%m-%d').date() if kwargs['purchaseDate'] else False
        if 'warrantyEndDate' in kwargs:
            vals['warranty_end_date'] = datetime.strptime(kwargs['warrantyEndDate'], '%Y-%m-%d').date() if kwargs['warrantyEndDate'] else False
        if 'usageFrequency' in kwargs:
            vals['usage_frequency'] = kwargs['usageFrequency']
        if 'usageHours' in kwargs:
            vals['usage_hours'] = float(kwargs['usageHours'])
        if 'remark' in kwargs:
            vals['remark'] = kwargs['remark']
        
        equipment.write(vals)
        
        return {
            'code': 200,
            'msg': '操作成功',
            'data': None
        }

    @http.route('/api/equipment/delete', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    @verify_api_token
    # @check_api_permission('device:equipment:delete')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def delete_equipment(self, **kwargs):
        """删除设备"""
        equipment_ids = kwargs.get('equipmentIds', [])
        if not equipment_ids:
            raise ValidationError('请选择要删除的设备')
        
        equipments = request.env['device.equipment'].sudo().browse(equipment_ids)
        equipments.unlink()
        
        return {
            'code': 200,
            'msg': '操作成功',
            'data': None
        }

    @http.route('/api/equipment/export', type='http', auth='none', methods=['GET'], csrf=False, cors='*')
    @verify_api_token
    # @check_api_permission('device:equipment:export')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def export_equipment(self, **kwargs):
        """导出设备信息"""
        # 获取查询条件
        name = kwargs.get('name', '')
        code = kwargs.get('code', '')
        status = kwargs.get('status', '')
        department_id = kwargs.get('departmentId', '')
        category_id = kwargs.get('categoryId', '')
        
        domain = []
        if name:
            domain.append(('name', 'ilike', name))
        if code:
            domain.append(('code', 'ilike', code))
        if status:
            domain.append(('status', '=', status))
        if department_id:
            domain.append(('department_id', '=', int(department_id)))
        if category_id:
            domain.append(('category_id', '=', int(category_id)))
        
        # 部门权限过滤
        current_user = getattr(request, 'current_api_user', None)
        if current_user:
            # 检查是否是admin账号，admin账号拥有全部权限
            # 检查用户ID是否为1（超级用户），或者login是否为admin
            is_admin = (current_user.id == 1 or current_user.login == 'admin')
            if is_admin:
                # admin账号可以看到所有设备，不添加过滤条件
                pass
            else:
                user_department = current_user.department_id
                if user_department:
                    # 检查用户是否是部门负责人
                    is_department_leader = user_department.leader_id and user_department.leader_id.id == current_user.id
                    
                    if is_department_leader:
                        # 部门负责人：可以看到该部门下的所有设备
                        domain.append(('department_id', '=', user_department.id))
                    else:
                        # 非部门负责人：只能看到设备绑定用户为自己的设备
                        domain.append(('user_id', '=', current_user.id))
                else:
                    # 没有部门信息，只能看到绑定给自己的设备
                    domain.append(('user_id', '=', current_user.id))
        
        equipments = request.env['device.equipment'].sudo().search(domain)
        
        # 构建Excel数据
        import xlsxwriter
        output = io.BytesIO()
        workbook = xlsxwriter.Workbook(output)
        worksheet = workbook.add_worksheet('设备信息')
        
        # 设置标题
        headers = [
            '设备编号', '设备名称', '设备型号', '设备类别', '所属部门', '车间位置',
            '设备使用人', '设备状态', '购买日期', '保修截止时间', '最近维护时间',
            '使用频率', '使用时长(小时)', '维保次数', '培训次数', '巡检次数', '报修次数',
            '创建时间', '备注'
        ]
        
        # 写入标题
        for col, header in enumerate(headers):
            worksheet.write(0, col, header)
        
        # 写入数据
        for row, equipment in enumerate(equipments, 1):
            data = [
                equipment.code,
                equipment.name,
                equipment.model or '',
                equipment.category_name or '',
                equipment.department_id.name if equipment.department_id else '',
                equipment.workshop_id.name if equipment.workshop_id else '',
                equipment.user_id.nick_name if equipment.user_id else '',
                dict(equipment._fields['status'].selection)[equipment.status],
                equipment.purchase_date.strftime('%Y-%m-%d') if equipment.purchase_date else '',
                equipment.warranty_end_date.strftime('%Y-%m-%d') if equipment.warranty_end_date else '',
                equipment.last_maintenance_date.strftime('%Y-%m-%d %H:%M:%S') if equipment.last_maintenance_date else '',
                dict(equipment._fields['usage_frequency'].selection)[equipment.usage_frequency],
                equipment.usage_hours,
                equipment.maintenance_count,
                equipment.training_count,
                equipment.inspection_count,
                equipment.repair_count,
                equipment.create_time.strftime('%Y-%m-%d %H:%M:%S') if equipment.create_time else '',
                equipment.remark or ''
            ]
            
            for col, value in enumerate(data):
                worksheet.write(row, col, value)
        
        workbook.close()
        output.seek(0)
        
        # 生成文件名
        filename = f"设备信息_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
        
        response = request.make_response(
            output.getvalue(),
            headers=[
                ('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'),
                ('Content-Disposition', f'attachment; filename="{filename}"')
            ]
        )
        output.close()
        return response

    # ==================== 选项数据 ====================
    
    @http.route('/api/equipment/categories', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    @verify_api_token
    # @check_api_permission('device:category:list')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def get_categories(self, **kwargs):
        """获取设备类别列表"""
        categories = request.env['device.category'].sudo().search([('status', '=', True)])
        data = []
        for category in categories:
            data.append({
                'categoryId': category.id,
                'categoryName': category.complete_name,
                'categoryCode': category.code,
                'parentId': category.parent_id.id if category.parent_id else None
            })
        
        return {
            'code': 200,
            'msg': '查询成功',
            'data': data
        }

    @http.route('/api/equipment/workshops', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    @verify_api_token
    # @check_api_permission('device:workshop:list')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def get_workshops(self, **kwargs):
        """获取车间列表"""
        workshops = request.env['device.workshop'].sudo().search([('status', '=', True)])
        data = []
        for workshop in workshops:
            data.append({
                'workshopId': workshop.id,
                'workshopName': workshop.name,
                'workshopCode': workshop.code,
                'departmentId': workshop.department_id.id if workshop.department_id else None,
                'departmentName': workshop.department_id.name if workshop.department_id else ''
            })
        
        return {
            'code': 200,
            'msg': '查询成功',
            'data': data
        }
